import { PDFDocument } from "pdf-lib";
import { Page } from "puppeteer";

const addScreenShotToPage = async (page: Page, pdfDoc: PDFDocument, xpath: string) => {
    // 获取元素的包围框
    const [elementHandle] = await page.$x(xpath);
    const boundingBox = await elementHandle.boundingBox();
    if (!boundingBox) return;
    // 生成包含元素的 PDF
    const screenshotBuffer = await page.screenshot({
        clip: {
            x: boundingBox.x,
            y: boundingBox.y,
            width: boundingBox.width,
            height: boundingBox.height,
        },
    });

    const pdfImage = await pdfDoc.embedPng(screenshotBuffer);

    // 创建新页面并绘制图像
    const newPage = pdfDoc.addPage([boundingBox.width, boundingBox.height]);

    newPage.drawImage(pdfImage, {
        x: -12,
        y: 0,
        width: boundingBox.width,
        height: boundingBox.height,
    });
}

// const pdfDoc = await PDFDocument.create();

// await addScreenShotToPage(page, pdfDoc, `/html/body/main/aside/div[1]/i/a/img`);
// await addScreenShotToPage(page, pdfDoc, `/html/body/main/div/div[2]`);
// // 保存新文档
// const finalPdfBuffer = await pdfDoc.save();
// fs.writeFileSync(`./pdf/${Date.now()}.pdf`, finalPdfBuffer);